import { PageProps } from "@/interfaces/app.interface"
import React, { useEffect, useCallback, useState, useRef, MouseEvent } from "react"
import style from "./index.less"
import Head from '../components/head'
import data from './data'
import {getMenu, gethall, getDefault} from '@/api'
import { throttle } from 'lodash'
const nav = [
    "大数据",
    "智慧城市",
    "新品发布",
    "核心产品",
    "新业务",
    "智慧应急",
    "智慧警务",
    "智慧司法",
    "社会治理",
    "城市停车",
    "智慧交管",
    "智慧交通",
    "公共民生",
    "智慧能源",
    "智慧制造",
    "智慧物流",
    "智慧园区",
    "智慧建筑",
    "智慧零售",
    "智慧金融",
    "智慧医疗",
    "智慧教育",
    "智慧文旅",
    "智慧农业",
    "SMB",
    "智慧生活",
]
const PI = Number((Math.PI / 13).toFixed(3))
let model: any = null
const ModelPage = (props: PageProps) => {

    let [rad, setRad] = useState(0)
    let [cur, setCur] = useState(9)
    let [mark, setMark] = useState(true)
    let [list, setList] = useState([])
    let [per, setPer] = useState([])
    let [show, setShow] = useState(true)
    let [remove, setRemove] = useState(false)
    let pref = useRef<any>()
    let ref = useRef<any>()

    let exhibitionId = props.location.query.i as string
    const getData = useCallback(
        (exhibitionId) => {
            let json = { exhibitionId }
            getMenu(json).then(res => {
                // console.log(res)
                if (res[7].isDel === 0) {
                    setPer(res)
                    setShow(false)
                    gethall(json).then(res => {
    
                        model = new (window as any).JMYDModel({
                            url: 'model.jm2',
                            // url: 'jm3/01.jm3',
                            el: '#model',
                            progress: (e: any) => {
                                // console.log(e)
                                ref.current.style.width = (e.loaded / e.total) * 100 + "%";
                            },
                            data: () => {
                                // return {type: 'jm3_'}
                               let arr = res.slice().sort((a, b) => a.industryId - b.industryId)
                               data.restoredCameras.forEach((item: obj, index) => {
                                    item.name = arr[index].title
                                    item.isshow = arr[index].state == 1
                                })
                                return data
                            },
                            loaded: () => {
                                console.log('load')
                                pref.current.classList.add('hide')
                                // model.hotspotPass.isshow = true;
                                // model.hotspotPass.initHotSpot();
                                model.playCurAnimation();

                                // model.control.minPolarAngle = Math.PI * 2;
                                model.control.maxPolarAngle = Math.PI / 2.1;

        
                                setTimeout(() => {
    
                                    model.beforeFly()
                                   
                                    setRemove(true)
                                }, 100)
                                let json = '[[0,1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20],[21,22,23,24,25,26,27,28]]'
                                model.playexcessivehotpot(1,json)
                            }
                        })
    
                        model.on('hotspotSelected', (obj: any) => {
                            console.log(obj)
                            if (obj.evtType == '_USR') {
                                open('/model/detail.html')
                            }
                        })
                        setList(res)
                    })
            
                }
            })
        },
        []
    )
    useEffect(() => {
        if (exhibitionId) {
            getData(exhibitionId)
        } else {
            getDefault().then(getData)
        }
    }, [])

    const hot = (item: obj) => () => {
        if (item.state) {
            let index = item.industryId - 1
            model.hotspotPass.select(index);
        }
    }

    const mousedown = (e: MouseEvent) => {

        let y = e.clientY
        const move = throttle((e: any) => {
            let diff = e.clientY - y
            let _cur = cur - diff * 0.02
            if (_cur > 10 || _cur < 2.85) return;
            setCur(_cur)
            setRad(() => rad - diff / 70 * Math.PI)
        }, 50)

        document.addEventListener('mousemove', move, false)

        document.addEventListener('mouseup', e => {
            document.removeEventListener('mousemove', move)
        }, { once: true })
    }

    const wheel = throttle((e:MouseEvent) => {
        let {wheelDelta} = e.nativeEvent as any
        let diff = wheelDelta < 0 ? 5 : -5
        let _cur = cur - diff * 0.02
        if (_cur > 10 || _cur < 2.85) return;
        setCur(_cur)
        setRad(() => rad - diff / 70 * Math.PI)
    }, 50)

    return show ? null : <>
        <Head status={1} per={per} id={exhibitionId}/>
        <div id="model"></div>
        {
            mark ?
                <div className={`${style.open} flex-center`} onClick={() => setMark(false)}>
                    <div>导览</div>
                    <img src={require('@/assets/img/open.png')} alt="" />
                </div>
                :
                <div className={style.nav} onWheel={wheel}>
                    <div className={style.circle}>
                        {list.map((item, i) => {
                            let pad = (i + rad) % 26
                            if ( pad > 13 ) return null
                            let left = 300 * Math.sin(pad * PI);
                            let top = 360 - 360 * Math.cos(pad * PI);
                            return <div key={i} className={`${style.item} flex-start ${item.state ? style.on : ''}`} style={{ left, top }} onClick={hot(item)}>
                                <div className={`flex-center ${style.icon}`}>
                                <img src={require(`@/assets/hot/${item.industryId}.png`) } alt="" />    
                                </div>  {item.industryName}
                            </div>
                        })}

                    </div>
                    <div className={style.box}>
                        <div className={style.scroll}>
                            <div className={style.bar} onMouseDown={mousedown} style={{ top: 200 + 210 * Math.cos(cur * PI), left: 210 * Math.sin(cur * PI) - 10 }}>
                            </div>
                        </div>
                    </div>

                    <div className={`${style.close} flex-center`} onClick={() => setMark(true)}>
                        <img src={require('@/assets/img/close.png')} alt="" />
                    </div>

                </div>
        }
        {   remove ? null : 
            <div className={`flex-center ${style.loading}`} ref={pref}>
                <div className={style.bar}>
                    <div className={style.progress} ref={ref}></div>
                </div>
            </div>
        }
    </>
}

export default ModelPage